package com.example.common.domain.pojo.TypeHandler;

import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.JdbcType;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@MappedTypes(Map.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MapListJsonTypeHandler extends AbstractJsonTypeHandler<Map<String, List<String>>> {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected Map<String, List<String>> parse(String json) {
        try {
            if (json == null || json.isEmpty()) {
                return new HashMap<>();
            }
            // 解析为 Map<String, List<String>>
//            return objectMapper.readValue(json,
//                    objectMapper.getTypeFactory().constructParametricType(
//                            HashMap.class, String.class,
//                            objectMapper.getTypeFactory().constructParametricType(
//                                    List.class, String.class)));
            return objectMapper.readValue(json,
                    new TypeReference<Map<String, List<String>>>() {
                    });
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse JSON to Map<String, List<String>>", e);
        }
    }

    @Override
    protected String toJson(Map<String, List<String>> obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert Map<String, List<String>> to JSON", e);
        }
    }
}
